package net

import (
	"bytes"
	"encoding/binary"
	"strconv"
	"strings"
)

func Ntohl(msg []byte) (int32, error) {

	var result int32
	buf := bytes.NewReader(msg)
	err := binary.Read(buf, binary.BigEndian, &result)

	return result, err
}

func Ntohs(msg []byte) (int16, error) {

	var result int16
	buf := bytes.NewReader(msg)
	err := binary.Read(buf, binary.BigEndian, &result)

	return result, err
}

func CheckIpv4Addr(addr string) bool {

	ips := strings.Split(addr, ".")
	if len(ips) != 4 {
		return false
	}

	for _, v := range ips {
		ip, err := strconv.Atoi(v)
		if err != nil {
			return false
		}

		if ip > 255 || ip < 0 {
			return false
		}
	}

	return true
}
